package com.requiem.hist_group_manage_springboot.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.PhoneUtil;
import com.requiem.hist_group_manage_springboot.common.HttpParamUtil;
import com.requiem.hist_group_manage_springboot.common.LogUtil;
import com.requiem.hist_group_manage_springboot.common.PageUtil;
import com.requiem.hist_group_manage_springboot.constants.SystemConstants;
import com.requiem.hist_group_manage_springboot.exception.R;
import com.requiem.hist_group_manage_springboot.mapper.GroupLogMapper;
import com.requiem.hist_group_manage_springboot.mapper.GroupMapper;
import com.requiem.hist_group_manage_springboot.mapper.TeacherMapper;
import com.requiem.hist_group_manage_springboot.model.*;
import com.requiem.hist_group_manage_springboot.service.TeacherService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TeacherServiceImpl implements TeacherService {


    @Autowired
    TeacherMapper teacherMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    GroupLogMapper groupLogMapper;
    @Autowired
    HttpParamUtil httpParamUtil;
    @Autowired
    LogUtil logUtil;
    @Autowired
    PageUtil pageUtil;

    @Override
    public R getList() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        Map<String, Object> result = pageUtil.executePageQuery(params, () -> teacherMapper.getTeacherList());
        return R.success(result);
    }

    @Override
    public R getByID() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));

        TeacherModel teacher = teacherMapper.getTeacherByID(id);
        return R.success(teacher);
    }

    @Override
    public R getLog() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));
        List<GroupLogModel> log = groupLogMapper.getLog(null, id, null);
        for (GroupLogModel groupLogModel : log) {
            String logStr = groupLogModel.getLog();
            String simpleLog = logStr.replaceAll("在.*?时", "");
            groupLogModel.setLog(simpleLog);
        }
        return R.success(log);
    }

    @Override
    public R add(@NonNull TeacherModel teacherModel) {
        String card = teacherModel.getIdCard();
        TeacherModel teacherGroup = teacherMapper.getTeacherExit(card);
        if (teacherGroup != null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        if (card != null) {
            if (!IdcardUtil.isValidCard(card) || !PhoneUtil.isPhone(teacherModel.getPhone())) {
                return R.error(SystemConstants.PARAM_ERROR, SystemConstants.PARAM_SDCARD_ERROR_MSG);
            }
            IdcardUtil.Idcard sdcardInfo = IdcardUtil.getIdcardInfo(card);
            DateTime birthDate = sdcardInfo.getBirthDate();
            LocalDate localDate = birthDate.toInstant().atZone(ZoneId.systemDefault()) // 系统默认时区
                    .toLocalDate();
            int age = sdcardInfo.getAge();
            Integer gender = sdcardInfo.getGender();
            if (teacherModel.getAge() == null) {
                teacherModel.setAge(age);
            }
            if (teacherModel.getSex() == null) {
                teacherModel.setSex(gender);
            }
            if (teacherModel.getBirthday() == null) {
                teacherModel.setBirthday(localDate);
            }
        }
        if (teacherModel.getCreateTime() == null) {
            teacherModel.setCreateTime(LocalDateTime.now());
        }
        int i = teacherMapper.addTeacher(teacherModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R delete() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));
        TeacherModel teacher = teacherMapper.getTeacherByID(id);
        if (teacher == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        if (teacher.getGroupId() != null) {
            exitGroup(id, teacher.getGroupId());
        }
        int i = teacherMapper.deleteTeacher(id);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R edit(@NonNull TeacherModel teacherModel) {
        TeacherModel teacher = teacherMapper.getTeacherByID(teacherModel.getId());
        if (teacher == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        String card = teacherModel.getIdCard();
        if (!IdcardUtil.isValidCard(card) || !PhoneUtil.isPhone(teacherModel.getPhone())) {
            return R.error(SystemConstants.PARAM_ERROR, SystemConstants.PARAM_SDCARD_ERROR_MSG);
        }
        IdcardUtil.Idcard sdcardInfo = IdcardUtil.getIdcardInfo(card);
        DateTime birthDate = sdcardInfo.getBirthDate();
        LocalDate localDate = birthDate.toInstant().atZone(ZoneId.systemDefault()) // 系统默认时区
                .toLocalDate();
        int age = sdcardInfo.getAge();
        Integer gender = sdcardInfo.getGender();
        teacherModel.setAge(age);
        teacherModel.setSex(gender);
        teacherModel.setBirthday(localDate);
        teacherModel.setCreateTime(LocalDateTime.now());
        int i = teacherMapper.editTeacher(teacherModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R joinGroup(int teacherId, String groupID) {
        String[] split = groupID.split(",");
        for (String id : split) {
            //小组人数加一，热度加一
            int groupId = Integer.parseInt(id);
            int teacherGroup = teacherMapper.getTeacherGroup(groupId, teacherId);
            if (teacherGroup != 0) {
                return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_GROUP_MSG);
            }
            GroupModel group = groupMapper.getGroupByID(groupId);
            if (group == null) {
                return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
            }
            if (group.getNumber() == null) {
                group.setNumber(0);
            }
            group.setNumber(group.getNumber() + 1);
            int i = groupMapper.editGroup(group);
            if (i < 1) {
                return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
            }
            logUtil.recordTeacher(teacherId, groupId, SystemConstants.JOIN_GROUP);
            int i1 = teacherMapper.addGroup(groupId, teacherId);
            if (i1 < 1) {
                return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
            }
        }
        return R.success();
    }

    @Override
    public R exitGroup(int teacherId, String groupID) {
        String[] split = groupID.split(",");
        for (String id : split) {
            int groupId = Integer.parseInt(id);
            int teacherGroup = teacherMapper.getTeacherGroup(groupId, teacherId);
            if (teacherGroup == 0) {
                return R.error(SystemConstants.DATA_NOT_EXIST, SystemConstants.DATA_DUPLICATE_EXITGROUP_MSG);
            }
            //小组人数加一，热度加一
            GroupModel group = groupMapper.getGroupByID(groupId);
            if (group == null) {
                return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
            }
            if (group.getNumber() == null) {
                group.setNumber(0);
            }
            if (group.getNumber() == 0) {
                return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_EXITGROUP_MSG);
            }
            group.setNumber(group.getNumber() - 1);
            int i = groupMapper.editGroup(group);
            if (i < 1) {
                return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
            }
            logUtil.recordTeacher(teacherId, groupId, SystemConstants.EXIT_GROUP);
            int i1 = teacherMapper.deleteGroup(groupId, teacherId);
            if (i1 < 1) {
                return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
            }
        }
        return R.success();
    }

    @Override
    public R SearchList(TeacherModel teacherModel) {
        Map<String, String> params = httpParamUtil.parseQueryString();
        Map<String, Object> result = pageUtil.executePageQuery(params, () -> teacherMapper.getSearchList(teacherModel));
        return R.success(result);
    }

    /*
     * 评论功能
     */
    @Override
    public R getStudent(String groupId) {
        String[] split = groupId.split(",");
        List<StudentModel> allStudents = new ArrayList<>();

        for (String id : split) {
            if (id == null || id.trim().isEmpty()) {
                continue;
            }
            try {
                int groupIdInt = Integer.parseInt(id.trim());
                List<StudentModel> students = teacherMapper.getStudent(groupIdInt);
                if (students != null && !students.isEmpty()) {
                    allStudents.addAll(students);
                }
            } catch (NumberFormatException e) {
                return R.error(SystemConstants.PARAM_ERROR, SystemConstants.PARAM_ERROR_MSG);
            }
        }
        return R.success(allStudents);
    }

    @Override
    public R getEvaluation(int teacherId) {
        List<EvaluationModel> evaluations = teacherMapper.getEvaluation(teacherId);
        for (EvaluationModel evaluationModel : evaluations) {
            if (evaluationModel.getEvaluation() == null) {
                continue;
            }
            String[] parts = evaluationModel.getEvaluation().split("\\|", 3);
            // 确保分割后有足够的部分
            if (parts.length >= 3) {
                if (evaluationModel.getStudentName() == null) {
                    evaluationModel.setStudentName(parts[0]);
                }
                if (evaluationModel.getTeacherName() == null) {
                    evaluationModel.setTeacherName(parts[1]);
                }
                evaluationModel.setEvaluation(parts[2]);
            }
        }

        return R.success(evaluations);
    }

    @Override
    public R addEvaluation(EvaluationModel evaluationModel) {
        evaluationModel.setType(SystemConstants.TEACHER_EVALUATION);
        evaluationModel.setCreateTime(LocalDateTime.now());
        String studentName = evaluationModel.getStudentName();
        String teacherName = evaluationModel.getTeacherName();
        String evaluation = evaluationModel.getEvaluation();
        String evaluationStr = new StringBuilder().append(studentName).append("|").append(teacherName).append("|").append(evaluation).toString();

        evaluationModel.setEvaluation(evaluationStr);
        int i = teacherMapper.addEvaluation(evaluationModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R resetPassword(int id, String password) {
        if (id == 0 || password == null) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        String finalPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        int i = teacherMapper.resetPassword(id, finalPassword);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

}
